<template>
    <div>
        <div class="container">
            <div class="handle-box">
                <div>
                    <el-input v-model="query.keywords" placeholder="关键词" class="handle-input mr10"></el-input>
                    <el-select v-model="query.type" class="m-2 mr10" placeholder="请选择类型" size="large">
                        <el-option key="0" label="全部类型" value="0" />
                        <el-option v-for="bartype in barTypes" :key="bartype.dic_vlu" :label="bartype.dic_vlu"
                            :value="bartype.dic_key" />
                    </el-select>
                    <el-button type="primary" size="small" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                </div>
                <div>
                    <el-button type="primary" size="small" icon="el-icon-plus" @click="handleCreate" class="add-btn">
                        添加内容</el-button>
                </div>
            </div>
            <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header"
                :cell-style="{padding:'3px 0'}">
                <el-table-column prop="edu_id" label="ID" width="55" align="center"></el-table-column>
                <el-table-column prop="edu_cover_title" align="center" label="封面标题"></el-table-column>
                <el-table-column prop="depart_name" align="center" label="部门"></el-table-column>
                <el-table-column prop="edu_cover_url" align="center" label="封面地址"></el-table-column>
                <el-table-column prop="edu_cover_cxt" align="center" label="封面简要"></el-table-column>
                <el-table-column prop="edu_tags" align="center" label="关键词"></el-table-column>
                <el-table-column label="操作" width="230" align="center">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">编辑
                        </el-button>
                        <el-button type="danger" size="small" @click="handleDelete(scope.$index, scope.row)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination background layout="total, prev, pager, next" :current-page="query.page"
                    :page-size="query.limit" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
            </div>
        </div>

        <!-- 添加弹出框 -->
        <el-dialog title="添加" v-model="addVisible" width="50%">
            <el-form label-width="110px">
                <el-form-item label="部门">
                    <el-select v-model="createForm.depart_id" class="m-2" placeholder="请选择部门" size="large">
                        <el-option v-for="item in departs" :key="item.depart_id" :label="item.depart_name"
                            :value="item.depart_id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="类型">
                    <el-radio-group v-model="createForm.edu_type" class="ml-4">
                        <el-radio v-for="item in barTypes" :label="item.dic_key"
                            size="large">{{item.dic_vlu}}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="分类">
                    <el-radio-group v-model="createForm.edu_sort" class="ml-4">
                        <el-radio v-for="item in eduSorts" :label="item.id" size="large">{{item.title}}</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-row>
                    <el-col :span="18">
                        <el-form-item label="内容">
                            <el-input type="textarea" :rows="2" v-model="createForm.edu_url"
                                placeholder="内容链接或者html或者文本内容"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-upload :action="uploadApi" :show-file-list="false" :limit="1" :http-request="afterUrlUpload"
                            class="upload-demo">
                            <template #default>
                                <el-button size="small" type="primary">点击上传</el-button>
                            </template>
                        </el-upload>
                    </el-col>
                </el-row>

                <el-form-item label="封面标题">
                    <el-input type="textarea" :rows="2" v-model="createForm.edu_cover_title"></el-input>
                </el-form-item>
                <el-form-item label="封面地址">
                    <el-input type="textarea" :rows="2" v-model="createForm.edu_cover_url"></el-input>
                </el-form-item>
                <el-form-item label="封面简要">
                    <el-input type="textarea" :rows="2" v-model="createForm.edu_cover_cxt"></el-input>
                </el-form-item>
                <el-form-item label="关键词">
                    <el-input type="textarea" :rows="2" v-model="createForm.edu_tags" placeholder="逗号，分割"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveCreate">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" v-model="editVisible" width="50%">
            <el-form label-width="110px">
                <el-form-item label="部门">
                    <el-select v-model="eidtForm.info.depart_id" class="m-2" placeholder="请选择部门" size="large">
                        <el-option v-for="item in departs" :key="item.depart_id" :label="item.depart_name"
                            :value="item.depart_id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="类型">
                    <el-radio-group v-model="eidtForm.info.edu_type" class="ml-4">
                        <el-radio v-for="item in barTypes" :label="item.dic_key"
                            size="large">{{item.dic_vlu}}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="分类">
                    <el-radio-group v-model="eidtForm.info.edu_sort" class="ml-4">
                        <el-radio v-for="item in eduSorts" :label="item.id" size="large">{{item.title}}</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-row>
                    <el-col :span="18">
                        <el-form-item label="内容">
                            <el-input type="textarea" :rows="2" v-model="eidtForm.info.edu_url"
                                placeholder="内容链接或者html或者文本内容"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-upload :action="uploadApi" :show-file-list="false" :limit="1" :http-request="afterEditUpload"
                            class="upload-demo">
                            <template #default>
                                <el-button size="small" type="primary">点击上传</el-button>
                            </template>
                        </el-upload>
                    </el-col>
                </el-row>

                <el-form-item label="封面标题">
                    <el-input type="textarea" :rows="2" v-model="eidtForm.info.edu_cover_title"></el-input>
                </el-form-item>
                <el-form-item label="封面地址">
                    <el-input type="textarea" :rows="2" v-model="eidtForm.info.edu_cover_url"></el-input>
                </el-form-item>
                <el-form-item label="封面简要">
                    <el-input type="textarea" :rows="2" v-model="eidtForm.info.edu_cover_cxt"></el-input>
                </el-form-item>
                <el-form-item label="关键词">
                    <el-input type="textarea" :rows="2" v-model="eidtForm.info.edu_tags" placeholder="逗号，分割"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveEdit">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
    import { ref, reactive } from "vue";
    import { ElMessage, ElMessageBox } from "element-plus";
    import { departAll,eduList, eduCreate, eduUpdate, dictEduType,uploadFile } from "../api/index";
    import { typeName, log } from "../utils/user"
    import { baseApi } from "../utils/request"



    export default {
        name: "basetable",
        setup() {
            const uploadHost = "https://med.medte.com.cn/storage/";
            const uploadApi = baseApi + "/uploadFile"

            const statusText = ["禁用", "启用"]
            const typeNames = typeName();

            let typeText = {};
            Object.keys(typeNames).forEach(k => {
                typeText[typeNames[k][0]] = typeNames[k][1]
            })
            log("typeText", typeText);

            const query = reactive({
                keywords: "",
                type: '0',
                page: 1,
                limit: 15,
            });
            const departs = ref([]);
            const adviceTypes = ref([])
            const tableData = ref([]);
            const pageTotal = ref(0);

            // 获取表格数据
            const getData = () => {
                eduList(query).then((res) => {
                    if (res.status == 'ok') {
                        adviceTypes.value = res.data.type
                        tableData.value = res.data.list.list;
                        pageTotal.value = res.data.list.pageTotal || 1;
                    } else {
                        ElMessage.error(res.msg)
                        return false;
                    }
                });
            };
            getData();

            // 查询操作
            const handleSearch = () => {
                query.page = 1;
                getData();
            };
            // 分页导航
            const handlePageChange = (val) => {
                query.page = val;
                getData();
            };

            // 删除操作
            const handleDelete = (index) => {
                // 二次确认删除
                ElMessageBox.confirm("确定要删除吗？", "提示", {
                    type: "warning",
                })
                    .then(() => {
                        ElMessage.success("删除成功");
                        tableData.value.splice(index, 1);
                    })
                    .catch(() => { });
            };
            const barTypes = ref([])
            const getTypeData = () => {
                dictEduType({}).then(res => {
                    if (res.status == 'ok') {
                        barTypes.value = res.data
                    }
                })
            };
            getTypeData()

            const getBarType = id => {
                let bartype = barTypes.find(v => v.dic_id == id);
                return bartype.dic_vlu
            }
            const eduSorts = [
                {
                    id: "1",
                    title: "富文本"
                },
                {
                    id: "2",
                    title: "链接地址 "
                },
                {
                    id: "3",
                    title: "视频"
                },
                {
                    id: "4",
                    title: "pdf"
                },
                {
                    id: "5",
                    title: "word"
                },
            ]
            const getEduSort = id => {
                let periodType = eduSorts.find(v => v.id == id);
                return periodType.title
            }
            // 表格添加
            const addVisible = ref(false);
            const handleCreate = () => {
                if (departs.value.length == 0) {
                    departAll({}).then(res => {
                        if (res.status == 'ok') {
                            departs.value = res.data;
                            log(departs)
                            addVisible.value = true;
                        } else {
                            ElMessage.error(res.msg)
                            return false;
                        }
                    })
                }else{
                    addVisible.value = true;
                }
            };

            let createForm = reactive({
                edu_sort: "1",
                edu_url: "",
                edu_cover_title: "",
                edu_cover_url: "",
                edu_cover_cxt: "",
                edu_type: "",
                edu_tags: "",
                depart_id: ""
            });

            const saveCreate = () => {
                if (!createForm.edu_type) {
                    ElMessage.error('请选择类型')
                    return false;
                }


                eduCreate(createForm).then(res => {
                    if (res.status == 'ok') {
                        addVisible.value = false;
                        ElMessage.success(res.msg);
                        query.pageIndex = 1;
                        getData();
                    } else {
                        ElMessage.error(res.msg)
                    }
                })
            }


            // 表格编辑时弹窗和保存
            const editVisible = ref(false);
            let eidtForm = reactive({
                id: 0,
                info: {
                    edu_sort: "1",
                    edu_url: "",
                    edu_cover_title: "",
                    edu_cover_url: "",
                    edu_cover_cxt: "",
                    edu_type: "",
                    edu_tags: "",
                    depart_id: ""
                }
            });
            let idx = -1;
            const handleEdit = (index, row) => {
                idx = index;
                eidtForm.info.edu_sort = row["edu_sort"];
                eidtForm.info.edu_url = row["edu_url"];
                eidtForm.info.edu_cover_title = row["edu_cover_title"];
                eidtForm.info.edu_cover_url = row["edu_cover_url"];
                eidtForm.info.edu_cover_cxt = row["edu_cover_cxt"];
                eidtForm.info.edu_type = row["edu_type"];
                eidtForm.info.edu_tags = row["edu_tags"];
                eidtForm.info.depart_id = row["depart_id"];
                eidtForm.id = row["edu_id"];

                 if (departs.value.length == 0) {
                    departAll({}).then(res => {
                        if (res.status == 'ok') {
                            departs.value = res.data;
                            editVisible.value = true;
                        } else {
                            ElMessage.error(res.msg)
                            return false;
                        }
                    })
                }else{
                    editVisible.value = true;
                }
            };
            const saveEdit = () => {
                if (!eidtForm.info.edu_type) {
                    ElMessage.error('请选择类型')
                    return false;
                }
                eduUpdate(eidtForm).then(res => {
                    if (res.status == 'ok') {
                        editVisible.value = false;
                        ElMessage.success(res.msg);
                        getData();
                    } else {
                        ElMessage.error(res.msg)
                    }
                })

            };
            const toggleStatus = (id, status) => {
                log("toggleStatus", id)
                let temp = {
                    id: id,
                    info: {
                        status: status
                    }
                }

                ElMessageBox.confirm("确认修改吗", "提示", {
                    type: "warning",
                })
                    .then(() => {
                        accountUpdate(temp).then(res => {
                            if (res.status == 'ok') {
                                ElMessage.success(res.msg)
                                getData();
                                return false;
                            } else {
                                ElMessage.error(res.msg)
                                return false;
                            }
                        })
                    })
                    .catch(() => { });


            }
            const getAdviceType = id => {
                let advice = adviceTypes.value.find(v => v.dic_key == id);
                return advice ? advice.dic_vlu : id
            }

            const afterUrlUpload = (item) => {
                uploadFile(item, { folder: "video" }).then(res => {
                    if (res.data.status == 'ok') {
                        createForm.edu_url = res.data.data
                    } else {
                        ElMessage.error(res.data.msg)
                    }
                })
            }

            const afterEditUpload = (item) => {
                uploadFile(item, { folder: "video" }).then(res => {
                    if (res.data.status == 'ok') {
                        eidtForm.info.edu_url = res.data.data
                    } else {
                        ElMessage.error(res.data.msg)
                    }
                })
            }

            return {
                statusText,
                typeText,

                // data
                query,
                tableData,
                pageTotal,


                handleSearch,
                handlePageChange,
                handleDelete,

                editVisible,
                eidtForm,
                handleEdit,
                saveEdit,

                createForm,
                addVisible,
                handleCreate,
                saveCreate,

                toggleStatus,

                eduSorts,
                getEduSort,
                barTypes,
                getBarType,
                getAdviceType,
                afterUrlUpload,
                afterEditUpload,
                uploadApi,
                departs
            };
        },
    };
</script>

<style scoped>
    .handle-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }

    .table {
        width: 100%;
        font-size: 14px;
    }

    .red {
        color: #ff0000;
    }

    .mr10 {
        margin-right: 10px;
    }

    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }

    .m-radio {
        margin: 12px;
    }

    .upload-demo:deep(.el-upload--text) {
        width: 100px;
        height: 40px;
        border: none;
    }
</style>